<?php
	$mode_dir =  ((!defined('SHOP_DEVELOPER') || !constant('SHOP_DEVELOPER')) && version_compare(PHP_VERSION,'5.0','>=')?'model_v5':'model');
	require_once(CORE_DIR.'/'.$mode_dir.'/trading/mdl.cart.php');
	class mdl_collocAddon extends mdl_cart
	{
		function setMemColloc($member_id,$rule)
		{
			$aData['addon'] = $rule;
			$aRs = $this->db->query("SELECT * FROM sdb_collocate_goods_collocaddon WHERE member_id=".intval($member_id));
			$sSql = $this->db->getUpdateSql($aRs,$aData,true);
			return $this->db->exec($sSql);
		}

		function getMemColloc($member_id)
		{
			$sql = 'SELECT addon from sdb_collocate_goods_collocaddon where member_id='.intval($member_id);
			return $this->db->getRow($sql);
		}

		function splitAddon($sCookie='')
		{
			/*示例：'colloc,95,347,1274670317_267,4_268,5|colloc,96,541,1274670542_246,4_248,5'; colloc,gid,pid,coid_copid,num
			分解后：[colloc,95,347,1274670317]=array([267]=>4,[268]=>5)
			*/
			if(!$sCookie){
				if($this->memberLogin){
					$sCookie = $this->getMemColloc($this->memInfo['member_id']);
				}else{
					$sCookie = $_COOKIE['colloc'];
				}
			}
			$data = explode('|',$sCookie);
			foreach ($data as $v)
			{
				$items = explode('_',$v);
				$colPref = $items['0'];		//colloc,95,367,1274670317
				unset($items['0']);
				foreach ($items as $i)
				{
					$aCo = explode(',',$i);
					$aColloc[$colPref][$aCo['0']] = $aCo['1'];
				}
			}
			return $aColloc;
		}
		
		/**
		 * 创建搭配商品addon数组信息
		 * @param array $data 示例参见 colloc.php
		 * @return array $aColloc
		 */
		function createRule($data)
		{
			$aColloc = $this->splitAddon();
			if (intval($data['product_id'] == 0))
			{
				$objGoods = &$this->system->loadModel('trading/goods');
				$aP = $objGoods->getProducts($gid);
				$pid = $aP[0]['product_id'];
			}
			if (isset($data['colloc']))
			{	
				//$colPref = 'colloc,'.$data['goods_id'].','.$pid;	//colloc,gid,pid,coId 示例：colloc,95,347,1274670317
				foreach ($data['colloc'] as $key => $var)
				{
					$colPref = 'colloc,'.$data['goods_id'].','.$pid.','.$key;	//colloc,gid,pid,coId 示例：colloc,95,347,1274670317
					foreach ($var as $k=>$v)
					{
						//在数据库的addon中是否已经存在 是：相加 否：赋值
						$num = isset($aColloc[$colPref][$k])?($aColloc[$colPref][$k]+$v):$v;
						//检查发配商品数量 在设置范围内 则更新addon 否则
						if ($this->checkCollocStore($data['goods_id'],$k,$key,$num,$aErr))
						{
							$aColloc[$colPref][$k] = $num;
						}
						else
						{
							trigger_error($aErr,E_USER_ERROR);
							return false;
						}
					}
				}
			}
			//$this->saveCollocCart($aColloc);
			return $aColloc;
		}

		function saveCollocCart($aCo)
		{
			foreach ($aCo as $key =>$var)
			{
				$prefix[] = $key;
				foreach ($var as $k =>$v)
				{
					$prefix[] = $k.','.$v;
				}
				$tmp[] = implode('_',$prefix);
			}
			$ruleStr = implode('|',$tmp);

			if ($this->memberLogin)
			{
				//$objCollocAddon = $this->system->loadModel('plugins/collocate_goods/collocaddon');
				$this->setMemColloc($this->member['member_id'],$ruleStr);
			}
			else
			{
				$this->system->setcookie('colloc',$ruleStr);
			}
			return true;
		}

		function getCollocProduct()
		{
			$objGoods = $this->system->loadModel('trading/goods');
			$objCollocGoods = $this->system->loadModel('plugins/collocate_goods/collocGoods');

			$aColloc = $this->splitAddon();
			//示例：$aColloc = array('colloc,95,347'=>array('267'=>3,'268'=>4),'colloc,96,541'=>array('247'=>3,'248'=>4));
			$collocTrading = array();
			foreach ($aColloc as $key =>$var)
			{
				$kData = explode(',',$key);
				$gid = $kData['1'];
				$rows = unserialize($objGoods->getGoodsMemo($gid,'collocation'));
				foreach ($var as $k =>$v)
				{
					if ('minus' == $rows['set_price'])
					{
						$cols = 'product_id,goods_id,name, pdt_desc, store, freez, price, price-'.intval($rows['price']).' AS colprice';
					}
					else
					{
						$cols = 'product_id,goods_id,name, pdt_desc, store, freez, price, price*'.($rows['price']?$rows['price']:1).' AS colprice';
					}
					$coProducts = $objCollocGoods->getCollocProducts($cols,$aPid);
					$coProducts['totalPrice'] = $coProducts['colprice']*$v;		//每个搭配商品的总价格等于colprice*数量
					//$collocTrading[$gid]['co_product'][] = $coProducts;	//把搭配商品信息带过去
					$coTotal += $coProducts['totalPrice'];
				}
				$collocTrading[$gid] = $rows;
				$collocTrading[$gid]['totalPrice'] = $coTotal;
			}
			return $collocTrading;
		}
		
		/** 
		 * 更新搭配商品的addon信息
		 * @param array $data 要更新的数据 $data：array([colloc,95,347,1274670317][267]=>2)
		 * @return bool
		 */
		function updateCollocAddon($data,&$aMsg)
		{
			//$data=[colloc,95,347,1274670317][267]=>2;
			$aCoAddon = $this->splitAddon();
			foreach ($data as $key =>$var)
			{
				$coKey = explode(',',$key);
				$gid = $coKey[1];
				$coid = $coKey[3];
				foreach ($var as $k=>$v)
				{
					if ($this->checkCollocStore($gid,$pid,$coid,$v,$aMsg))
					{
						$aCoAddon[$k] = $v;
					}
					else
					{
						trigger_error($aMsg,E_USER_ERROR);
						return false;
					}
				}
				/*
				if (isset($aCoAddon[$k]))
				{
					$aCoAddon[$k] = $v;
				}
				*/
			}
			return $this->saveCollocCart($aCoAddon);
			//return $aCoAddon;
		}

		function removeCollocAddon($rmData)
		{
			$aCoAddon = $this->splitAddon();
			foreach ($rmData as $k=>$v)
			{
				if (isset($aCoAddon[$k]))
				{
					unset($aCoAddon[$k]);
				}
			}
			$this->saveCollocCart($aCoAddon);
		}
		
		/**
		 * 检查搭配商品的库存
		 * @param string $gid 商品goods_id
		 * @param string $pid 搭配货品的id product_id
		 * @param string $coid 搭配组id
		 * @param int $num 数量
		 * @param string 错误信息
		 * @return bool
		 */
		function checkCollocStore($gid,$pid,$coid,$num,&$aErr)
		{
			$objGoods = $this->system->loadModel('trading/goods');
			$aCollocInfo = unserialize($objGoods->getGoodsMemo($gid,'collocation'));
			$objProduct = &$this->system->loadModel('goods/products');
			$aStore = $objProduct->getFieldById($pid);
			if(!is_null($aStore['store'])){
				$gStore = intval($aStore['store']) - intval($aStore['freez']);
				if($gStore < $num){
					$aErr = '商品库存不足';
					return false;
					exit;
				}
			}
			if (($num<=$aCollocInfo[$coid]['min_num']) || ($num>=$aCollocInfo[$coid]['max_num']))
			{
				$aErr = '小于最小购买量';
				return false;
				exit;
			}
			if (($num>=$aCollocInfo[$coid]['max_num']))
			{
				$aErr = '大于最大购买量';
				return false;
				exit;
			}
			return true;
		}

?>